require 'net/http'

#监控网站
SITES = [
  'http://www.iyaoi.cn/'
]

#收件邮箱
TO = 'liuzihua8@gmail.com,liuzihua8@163.com'

def check_sites
  SITES.each {|site| 
    #unless check_site(site)
      send_alarm_mail(site)
    #end
  }
end

def check_site(url)
  url = URI.parse(url)
  req = Net::HTTP::Get.new(url.path)
  res = Net::HTTP.start(url.host, url.port) {|http|
    http.request(req)
  }
  return res.code == '200' ? true : false
end

def send_alarm_mail(site)
  puts 'send alarm mail'
  subject = site + ' Down!'
  time = Time.now.strftime("%Y年%m月%d日 %H:%M:%S")
  content = '<h1>' + subject + "</h1><br/>检测时间：#{time}"
  Mailer.deliver_send(TO, subject, content)
end

def send_back_mail(site)
  subject = site ' back!'
  time = Time.now.strftime("%Y年%m月%d日 %H:%M:%S")
  content = '<h1>' + subject + "</h1><br/>检测时间：#{time}"
  Mailer.deliver_send(TO, subject, content)
end


namespace :app do
  
  desc "检测网站"
  task :check_sites => :environment do
    puts "check sites start."
    check_sites
    puts "check sites end."
  end
end


